package com.gs.pattern.iterator;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: gs
 * @Date: 2023/12/10 16:40
 * @Version: v1.0.0
 * @Description: TODO
 **/

/**
 * 学习：
 * 定义和用法
 * implements 关键字用于实现interface接口
 *
 * interface 关键字用于声明仅包含抽象方法的特殊类型的类。
 *
 * 关于接口的说明：
 *      不能用于创建对象
 *      接口方法没有主体（空方法）
 *      实现接口时，必须重写其所有方法
 *      默认情况下，接口方法是abstract抽象的和public公共的
 *      接口属性默认为public, static , final
 *      接口不能包含构造函数（因为它不能用于创建对象）
 *
 * **/

public class IteratorPatternDemo {

    public static void main(String[] args) {
        WithoutIteratorDemo.Student student1 = new WithoutIteratorDemo.Student("小明",10);
        WithoutIteratorDemo.Student student2 = new WithoutIteratorDemo.Student("小王",20);

        Classroom classroom = new Classroom(2);
        classroom.addStudent(student1);
        classroom.addStudent(student2);

        java.util.Iterator<WithoutIteratorDemo.Student> iterator = classroom.iterator();
        while(iterator.hasNext()) {
            WithoutIteratorDemo.Student student = (WithoutIteratorDemo.Student) iterator.next();
            System.out.println(student);
        }
    }

    /**
     * 定义一个我们自己的迭代器接口
     * @author
     *
     */
    public interface Iterator{
        public abstract boolean hashnext();
        public abstract Object next();
    }

    public interface Aggregate{
        public abstract java.util.Iterator<WithoutIteratorDemo.Student> iterator();
    }
    /**
     * 教室迭代器
     * @author zhonghuashishan
     *
     */
    public static class ClassIterator implements Iterator{
        private Classroom classroom;
        private int index;

        public ClassIterator(Classroom classroom){
            this.classroom = classroom;
            this.index = 0;
        }

        public boolean hashnext(){
            if(index < classroom.getLength()){
                return true;
            }else{
                return false;
            }
        }

        public Object next(){
            WithoutIteratorDemo.Student student = classroom.getStudent(index);
            index ++;
            return  student;
        }
    }
    /**
     * 教室类
     * @author zhonghuashishan
     *
     */
    public static class Classroom implements Aggregate{

        private List<WithoutIteratorDemo.Student> students;
        private int last = 0;

        public Classroom(int size){
            this.students = new ArrayList<WithoutIteratorDemo.Student>(2);
        }

        public WithoutIteratorDemo.Student getStudent(int index){
            return students.get(index);
        }

        public void addStudent(WithoutIteratorDemo.Student student) {
//	        this.students[last] = student;
            this.students.add(student);
            last++;
        }

        public int getLength(){
            return last;
        }
        public java.util.Iterator<WithoutIteratorDemo.Student> iterator(){
            return students.iterator();

        }
    }

}
